package com.hulizuofang.wol.chat.server.handler;

import java.util.logging.Level;
import java.util.logging.Logger;

import com.google.inject.Inject;
import com.gwtplatform.dispatch.server.ExecutionContext;
import com.gwtplatform.dispatch.server.actionhandler.ActionHandler;
import com.gwtplatform.dispatch.shared.ActionException;
import com.hulizuofang.wol.chat.client.action.SendChatAction;
import com.hulizuofang.wol.chat.client.action.SendChatAction.ChatWorker;
import com.hulizuofang.wol.chat.client.action.SendChatResult;
import com.hulizuofang.wol.chat.client.data.ChatUser;
import com.hulizuofang.wol.chat.server.channel.ChannelProvider;

public class SendChatActionHandler implements ActionHandler<SendChatAction, SendChatResult> {

	private static final Logger logger = Logger.getLogger(SendChatActionHandler.class.getName());
	
	private final ChannelProvider provider;

	@Inject
	public SendChatActionHandler(ChannelProvider provider) {
		this.provider = provider;
	}

	@Override
	public SendChatResult execute(SendChatAction action,
			ExecutionContext context) throws ActionException {
		return action.workChat(new ChatWorker<SendChatResult>() {
			@Override
			public SendChatResult work(ChatUser sender, ChatUser recipient,
					String message) {
				if (logger.isLoggable(Level.INFO)) {
					logger.info(String.format("Sending from '%s' to '%s' message '%s'", sender.getId(), recipient.getId(), message));
				}
				return new SendChatResult(provider.sendChat(sender, recipient, message));
			}
		});

	}

	@Override
	public Class<SendChatAction> getActionType() {return SendChatAction.class;}
	@Override
	public void undo(SendChatAction action, SendChatResult result, ExecutionContext context) throws ActionException {}

}
